package com.hnas.eastsquare.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component("jedisUtil")
public class JedisUtil {
	
//	@Value("#{component['redis_ip']}")//东方广场活动结束时间
	private String IP;//测试环境
//	@Value("#{component['redis_port']}")//东方广场活动结束时间
	private int PORT;
//	@Value("#{component['redis_auth']}")
	private String AUTH;
	
	private Logger logger = Logger.getLogger(this.getClass().getName());

	private JedisUtil() {
	}

	private static Map<String, JedisPool> maps = new HashMap<String, JedisPool>();

	private JedisPool getPool(String ip, int port) {
		String key = ip + ":" + port;
		JedisPool pool = null;
		if (!maps.containsKey(key)) {
			JedisPoolConfig config = new JedisPoolConfig();
			// config.setMaxActive(RedisConfig.MAX_ACTIVE);
			config.setMaxTotal(RedisConfig.MAX_ACTIVE);
			config.setMaxIdle(RedisConfig.MAX_IDLE);
			// config.setMaxWait(RedisConfig.MAX_WAIT);
			config.setMaxWaitMillis(RedisConfig.MAX_WAIT);
			config.setTestOnBorrow(false);
			config.setTestOnReturn(true);
		
			pool = new JedisPool(config, ip, port, RedisConfig.TIMEOUT);
			maps.put(key, pool);
		} else {
			pool = maps.get(key);
		}
		return pool;
	}

	public Jedis getJedis() {
		Jedis jedis = null;
		int count = 0;
		do {
			try {
				jedis = getPool(IP, PORT).getResource();
				jedis.auth(AUTH);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("get redis master1 failed!"+ e);
				getPool(IP, PORT).returnResourceObject(jedis);
			}
		} while (jedis == null && count < RedisConfig.RETRY_NUM);
		return jedis;
	}

	public void closeJedis(Jedis jedis) {
		if (jedis != null) {
			getPool(IP, PORT).returnResourceObject(jedis);
		}
	}

	private class RedisConfig {
		// 可用连接实例的最大数目，默认值为8；
		// 如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
		public static final int MAX_ACTIVE = 1024;

		// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
		public static final int MAX_IDLE = 5;

		// 等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException；
		public static final int MAX_WAIT = 10000;

		public static final int TIMEOUT = 10000;

		public static final int RETRY_NUM = 5;
	}
}
